﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using MVCms.Core.Developers;
using Plugin.UserFormsAuthentication.Models;

namespace Plugin.UserFormsAuthentication.Controllers
{
    [HandleError]
    public class AccountController : BaseController
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        [PluginModule(Name = "UserFormsAuthenticationLogon", Description = "User Forms Authentication Logon", DisplayName = "User Forms Authentication Logon")]
        public PartialViewResult LogOn()
        {
            return PartialView();
        }

        [HttpPost]
        public PartialViewResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    
                    //if a redirect url is present redirect to it, else, redirect to the home page
                    if (!String.IsNullOrEmpty(Session["ReturnUrl"].ToString()))
                    {
                        Response.Redirect(Session["ReturnUrl"].ToString());
                    }
                    else
                    {
                        Response.Redirect(MVCms.Core.Developers.SystemPage.Home.Url);
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return PartialView(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************
        [PluginModule(Name = "UserFormsAuthenticationLogoff", Description = "User Forms Authentication Logoff", DisplayName = "User Forms Authentication Logoff")]
        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return null;
        }

        // **************************************
        // URL: /Account/Register
        // **************************************
        [PluginModule(Name = "UserFormsAuthenticationRegister", Description = "User Forms Authentication Register", DisplayName = "User Forms Authentication Register")]
        public PartialViewResult Register()
        {
            //ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return PartialView();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    //return RedirectToAction("Index", "Home");
                    return Redirect(Request.UrlReferrer.ToString());
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            //ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return Redirect(Request.UrlReferrer.ToString()); //return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        //[Authorize]
        [PluginModule(Name = "UserFormsAuthenticationChangePassword", Description = "User Forms Authentication Change Password", DisplayName = "User Forms Authentication Password")]
        public PartialViewResult ChangePassword()
        {
            //ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return PartialView();
        }

        //[Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        [PluginModule(Name = "UserFormsAuthenticationLogonChangePasswordSuccess", Description = "User Forms Authentication Change Password Success", DisplayName = "User Forms Authentication Change Password Success")]
        public PartialViewResult ChangePasswordSuccess()
        {
            return PartialView();
        }

    }
}
